import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { message } from 'ant-design-vue'
import chatApi from '../api/chat'
import { useAuthStore } from './auth'
import { generateGuid } from '../utils/guid'

/**
 * 聊天状态管理模块
 * 负责聊天会话、消息、流式输出和文件上传的状态管理
 * 支持多会话窗口、实时消息流式输出和会话状态隔离
 */

export const useChatStore = defineStore('chat', () => {
  const sessions = ref([])
  const currentSession = ref(null)
  
  // 统一会话状态管理
  const sessionStates = ref(new Map()) // sessionId -> SessionState
  
  // 活跃会话管理
  const activeSessions = ref(new Set()) // 当前活跃的会话ID集合
  

  
  // 会话状态结构
  class SessionState {
    constructor(sessionId) {
      this.sessionId = sessionId
      this.messages = []
      this.loading = false
      this.isStreaming = false // 添加流式输出状态
      this.isActive = false
      this.inputMessage = '' // 每个会话独立的输入内容
      this.uploadedFiles = [] // 每个会话独立的文件列表
      this.hasAiResponded = false // 添加AI是否已开始输出的标志
      this.enableSearch = true // 每个会话独立的搜索开关状态，默认开启
    }
  }
  
  // 计算属性：获取当前活跃会话
  const activeSessionStates = computed(() => {
    const activeStates = []
    for (const sessionId of activeSessions.value) {
      const state = sessionStates.value.get(sessionId)
      if (state) {
        activeStates.push(state)
      }
    }
    return activeStates
  })
  
  // 计算属性：获取当前会话的消息
  const messages = computed(() => {
    if (!currentSession.value) return []
    const state = sessionStates.value.get(currentSession.value.id)
    return state ? state.messages : []
  })
  
  // 计算属性：获取当前会话的输入内容
  const inputMessage = computed({
    get: () => {
      if (!currentSession.value) return ''
      const state = sessionStates.value.get(currentSession.value.id)
      return state ? state.inputMessage : ''
    },
    set: (value) => {
      if (!currentSession.value) return
      const state = getOrCreateSessionState(currentSession.value.id)
      state.inputMessage = value
    }
  })
  
  // 计算属性：获取当前会话的文件列表
  const uploadedFiles = computed(() => {
    if (!currentSession.value) return []
    const state = sessionStates.value.get(currentSession.value.id)
    return state ? state.uploadedFiles : []
  })
  
  // 计算属性：获取当前会话的加载状态
  const loading = computed(() => {
    if (!currentSession.value) return false
    const state = sessionStates.value.get(currentSession.value.id)
    return state ? state.loading : false
  })
  
  // 计算属性：获取当前会话的流式输出状态
  const isStreaming = computed(() => {
    if (!currentSession.value) return false
    const state = sessionStates.value.get(currentSession.value.id)
    return state ? state.isStreaming : false
  })
  
  // 计算属性：获取当前会话的重试状态
  const isRetrying = computed(() => {
    if (!currentSession.value) return false
    const state = sessionStates.value.get(currentSession.value.id)
    return state ? state.isRetrying : false
  })
  
  // 计算属性：是否可以重试
  const canRetry = computed(() => {
    if (!currentSession.value) return false
    
    const currentState = getOrCreateSessionState(currentSession.value.id)
    if (!currentState.lastUserMessage) return false
    
    // 检查当前会话是否有AI消息，且不是流式输出状态
    const hasAiMessage = currentState.messages.some(msg => !msg.is_user)
    
    return hasAiMessage && !currentState.isStreaming
  })
  
  // 获取当前会话的流式控制器
  const currentStreamController = computed(() => {
    if (!currentSession.value) return null
    const state = sessionStates.value.get(currentSession.value.id)
    return state ? state.streamController : null
  })


  


  const fetchSessions = async () => {
    try {
      const response = await chatApi.getSessions()
      sessions.value = response
    } catch (error) {
      console.error('获取会话列表失败：', error)
      message.error('加载会话列表失败：' + (error.response?.data?.detail || error.message))
    }
  }

  // 获取或创建会话状态
  const getOrCreateSessionState = (sessionId) => {
    if (!sessionStates.value.has(sessionId)) {
      sessionStates.value.set(sessionId, new SessionState(sessionId))
    }
    return sessionStates.value.get(sessionId)
  }

  // 激活会话（将会话标记为活跃状态）
  const activateSession = (sessionId) => {
    console.log(`[前端日志] activateSession - 开始激活会话 ${sessionId}`)
    
    // 关键修复：确保只有一个会话是活跃状态
    // 停用所有其他会话，避免多个会话同时接收消息
    for (const activeSessionId of activeSessions.value) {
      if (activeSessionId !== sessionId) {
        console.log(`[前端日志] activateSession - 停用其他会话 ${activeSessionId}`)
        deactivateSession(activeSessionId)
      }
    }
    
    activeSessions.value.add(sessionId)
    const state = getOrCreateSessionState(sessionId)
    state.isActive = true
    console.log(`[前端日志] activateSession - 会话 ${sessionId} 已激活，活跃会话数: ${activeSessions.value.size}`)
  }

  // 停用会话（将会话标记为非活跃状态）
  const deactivateSession = (sessionId) => {
    console.log(`[前端日志] deactivateSession - 开始停用会话 ${sessionId}`)
    activeSessions.value.delete(sessionId)
    const state = sessionStates.value.get(sessionId)
    if (state) {
      state.isActive = false
      console.log(`[前端日志] deactivateSession - 会话 ${sessionId} 已停用，活跃会话数: ${activeSessions.value.size}`)
      
      // 关闭SSE连接，避免会话切换时流式输出同时显示
      if (state.eventSource) {
        console.log(`[前端日志] deactivateSession - 关闭SSE连接 - 会话ID: ${sessionId}`)
        state.eventSource.close()
        state.eventSource = null
      }
      
      // 停止流式输出状态
      state.isStreaming = false
      
      // 清理消息状态，避免重复显示
      console.log(`[前端日志] deactivateSession - 清理会话消息状态 - 会话ID: ${sessionId}`)
      
      // 重置流式消息状态，确保不会显示重复内容
      state.messages = state.messages.map(msg => ({
        ...msg,
        is_streaming: false,
        is_final: true
      }))
      
      // 重置AI响应状态
      state.hasAiResponded = false
    } else {
      console.log(`[前端日志] deactivateSession - 会话 ${sessionId} 状态不存在`)
    }
  }

  // 停止指定会话的流式输出
  const stopSessionStream = (sessionId) => {
    const state = sessionStates.value.get(sessionId)
    if (state) {
      if (state.streamController) {
        state.streamController.abort()
        state.streamController = null
      }
      state.isStreaming = false
    }
  }

  // 停止所有会话的流式输出
  const stopAllStreams = () => {
    for (const [sessionId, state] of sessionStates.value.entries()) {
      if (state.streamController) {
        state.streamController.abort()
        state.streamController = null
      }
      state.isStreaming = false
    }
  }

  const createSession = async () => {
    try {
      // 不传递标题，让后端根据第一条消息自动生成标题
      const response = await chatApi.createSession()
      const newSession = response
      sessions.value.unshift(newSession)
      
      // 创建新的会话状态并激活
      const newState = getOrCreateSessionState(newSession.id)
      activateSession(newSession.id)
      
      // 切换到新会话
      await selectSession(newSession.id)
      
      return newSession
    } catch (error) {
      console.error('创建会话失败：', error)
      message.error('创建会话失败：' + (error.response?.data?.detail || error.message))
      throw error
    }
  }

  const selectSession = async (sessionId) => {
    console.log(`[前端日志] selectSession - 开始切换会话 ${sessionId}`)
    
    // 关键修复：确保会话切换时完全清理旧会话状态
    // 停用所有其他会话，避免消息重复显示
    for (const activeSessionId of activeSessions.value) {
      if (activeSessionId !== sessionId) {
        console.log(`[前端日志] selectSession - 停用其他会话 ${activeSessionId}`)
        deactivateSession(activeSessionId)
        
        // 停止其他会话的流式输出
        stopSessionStream(activeSessionId)
        
        // 关闭其他会话的SSE连接
        const otherState = sessionStates.value.get(activeSessionId)
        if (otherState && otherState.eventSource) {
          console.log(`[前端日志] selectSession - 关闭其他会话SSE连接 ${activeSessionId}`)
          otherState.eventSource.close()
          otherState.eventSource = null
        }
      }
    }
    
    // 激活新会话
    console.log(`[前端日志] selectSession - 激活新会话 ${sessionId}`)
    activateSession(sessionId)
    
    // 更新当前会话
    currentSession.value = sessions.value.find(s => s.id === sessionId)
    
    // 加载会话消息
    console.log(`[前端日志] selectSession - 加载会话消息 ${sessionId}`)
    await loadSessionMessages(sessionId)
    
    // 检查是否需要恢复流式输出
    console.log(`[前端日志] selectSession - 检查流式状态 ${sessionId}`)
    await checkAndResumeStreaming(sessionId)
    
    console.log(`[前端日志] selectSession - 会话切换完成 ${sessionId}`)
  }

  const loadSessionMessages = async (sessionId) => {
    try {
      const state = getOrCreateSessionState(sessionId)
      
      // 尝试从后端加载消息
      const response = await chatApi.getSessionMessages(sessionId)
      
      // 处理消息数据
      const processedMessages = response.map(msg => ({
        ...msg,
        // 确保消息状态正确
        is_streaming: msg.is_streaming !== undefined ? msg.is_streaming : false,
        is_final: msg.is_final !== undefined ? msg.is_final : true
      }))
      
      // 更新消息列表
      state.messages = processedMessages
      
      state.isStreaming = false
    } catch (error) {
      console.error('加载会话消息失败：', error)
      message.error('切换会话失败：' + (error.response?.data?.detail || error.message))
      
      // 错误处理
      const state = getOrCreateSessionState(sessionId)
      if (state) {
        // 保留现有消息，不覆盖
        console.log(`保留现有消息，失败原因：${error.message}`)
      }
    } finally {
      // 不设置loading状态，避免页面闪烁
    }
  }





  // 为指定会话发送流式消息（支持并发）
  const sendMessageStreamToSession = async (sessionId, params) => {
    const targetState = getOrCreateSessionState(sessionId)
    let aiMessageId = null // 在函数作用域内定义aiMessageId
    
    // 检查页面是否正在卸载（刷新或关闭）
    let isPageUnloading = false
    const handleBeforeUnload = () => {
      isPageUnloading = true
    }
    window.addEventListener('beforeunload', handleBeforeUnload)
    
    // 设置目标会话的加载状态和流式输出状态
    targetState.loading = true
    targetState.isStreaming = true
    
    try {
      // 添加用户消息
      const userMessage = {
        id: generateGuid(),
        session_id: sessionId,
        content: params.content,
        message_type: params.messageType || 'text',
        is_user: true,
        created_at: new Date().toISOString(),
        file_path: params.filePath || null // 使用上传后的文件路径
      }
      
      targetState.messages.push(userMessage)

      // 创建AI消息占位符
      aiMessageId = generateGuid()
      const aiMessage = {
        id: aiMessageId,
        session_id: sessionId,
        content: '',
        message_type: 'text',
        is_user: false,
        created_at: new Date().toISOString(),
        file_path: null,
        is_streaming: true
      }
      
      targetState.messages.push(aiMessage)
      
      // 设置会话状态为流式处理中
      targetState.isStreaming = true

      // 发送到后端流式API
      const apiBaseUrl = import.meta.env.VITE_API_BASE_URL || 'http://localhost:8000'
      const authStore = useAuthStore()
      
      // 创建FormData对象 - 修复参数名：后端期望'message'和'message_type'
      const formData = new FormData()
      formData.append('message', params.content)
      formData.append('message_type', params.messageType || 'text')
      formData.append('enable_search', targetState.enableSearch.toString()) // 添加搜索开关状态
      
      // 处理文件上传 - 后端期望参数名为'file'
      if (params.file) {
        // 只处理第一个文件，因为后端接口只支持单个文件
        const fileObj = params.file
        if (fileObj.file) {
          formData.append('file', fileObj.file)
        } else {
          // 如果fileObj.file不存在，尝试直接使用fileObj
          formData.append('file', fileObj)
        }
      }
      
      // 创建AbortController
      const controller = new AbortController()
      targetState.streamController = controller
      
      const response = await fetch(`${apiBaseUrl}/chat/sessions/${sessionId}/send-message-stream`, {
        method: 'POST',
        headers: {
          'Authorization': `Bearer ${authStore.token}`
        },
        body: formData,
        signal: controller.signal
      })

      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`)
      }
      
      const reader = response.body.getReader()
      const decoder = new TextDecoder()
      let buffer = ''
      
      while (true) {
        const { done, value } = await reader.read()
        
        if (done) {
          break
        }
        
        const chunk = decoder.decode(value, { stream: true })
        buffer += chunk
        
        // 解析SSE格式数据
        const lines = buffer.split('\n')
        buffer = lines.pop() || '' // 保留未完成的行
        
        for (const line of lines) {
          if (line.startsWith('data: ')) {
            try {
              const data = JSON.parse(line.slice(6)) // 去掉 'data: ' 前缀
              
              if (data.error) {
                console.error('服务器返回错误：', data.error)
                throw new Error(data.error)
              }
              
              if (data.content) {
                // 更新AI消息内容
                const aiMessageIndex = targetState.messages.findIndex(msg => msg.id === aiMessageId)
                if (aiMessageIndex !== -1) {
                  targetState.messages[aiMessageIndex].content += data.content
                  
                  // 设置AI已开始输出的标志
                  if (!targetState.hasAiResponded) {
                    targetState.hasAiResponded = true
                  }

                }
              }
            } catch (error) {
              console.error('解析SSE数据失败：', error, '原始数据：', line)
            }
          }
        }
      }
      
      // 流式响应结束
      const aiMessageIndex = targetState.messages.findIndex(msg => msg.id === aiMessageId)
      if (aiMessageIndex !== -1) {
        targetState.messages[aiMessageIndex].is_streaming = false
        targetState.messages[aiMessageIndex].is_final = true
      }
      
      // 重置会话状态
      targetState.isStreaming = false
      targetState.hasAiResponded = false
      
      // 如果是第一条消息，刷新会话列表以获取更新后的标题
      if (targetState.messages.length <= 2) { // 用户消息 + AI消息
        try {
          await fetchSessions()
        } catch (error) {
          console.error('刷新会话列表失败：', error)
        }
      }
      
    } catch (error) {
        console.error(`发送流式消息到会话 ${sessionId} 失败：`, error)
        
        // 检查是否为网络中断错误（页面刷新导致的）
        const isNetworkAborted = error.name === 'AbortError' || 
                               error.message?.includes('aborted') || 
                               error.message?.includes('ERR_ABORTED') ||
                               error.message?.includes('network error') ||
                               error.message?.includes('NetworkError') ||
                               isPageUnloading
        
        // 更新AI消息为错误状态
        const aiMessageIndex = targetState.messages.findIndex(m => m.id === aiMessageId)
        if (aiMessageIndex !== -1) {
          targetState.messages[aiMessageIndex].is_streaming = false
          
          if (isNetworkAborted) {
            // 如果是网络中断错误（页面刷新），显示更友好的提示
            targetState.messages[aiMessageIndex].content = '连接中断，请重新发送消息。'
          } else {
            // 其他错误显示通用提示
            targetState.messages[aiMessageIndex].content = '抱歉，消息发送失败，请稍后重试。'
          }
        }
        
        // 重置会话状态
        targetState.isStreaming = false
        targetState.hasAiResponded = false
    } finally {
      // 清理事件监听器
      window.removeEventListener('beforeunload', handleBeforeUnload)
      
      targetState.loading = false
      targetState.isStreaming = false
      targetState.streamController = null
    }
  }

  // 获取指定会话的状态
  const getSessionState = (sessionId) => {
    return sessionStates.value.get(sessionId)
  }

  // 检查会话是否活跃
  const isSessionActive = (sessionId) => {
    return activeSessions.value.has(sessionId)
  }

  // 检查会话是否正在加载
  const isSessionLoading = (sessionId) => {
    const state = sessionStates.value.get(sessionId)
    return state ? state.loading : false
  }

  // 获取指定会话的消息列表
  const getSessionMessages = (sessionId) => {
    const state = sessionStates.value.get(sessionId)
    return state ? state.messages : []
  }

  // 获取指定会话的文件列表
  const getSessionFiles = (sessionId) => {
    const state = sessionStates.value.get(sessionId)
    return state ? state.uploadedFiles : []
  }

  // 获取指定会话的输入内容
  const getSessionInput = (sessionId) => {
    const state = sessionStates.value.get(sessionId)
    return state ? state.inputMessage : ''
  }

  // 获取指定会话的搜索开关状态
  const getSessionEnableSearch = (sessionId) => {
    const state = sessionStates.value.get(sessionId)
    return state ? state.enableSearch : true
  }

  // 设置指定会话的搜索开关状态
  const setSessionEnableSearch = (sessionId, enableSearch) => {
    const state = getOrCreateSessionState(sessionId)
    state.enableSearch = enableSearch
  }

  // 添加文件到指定会话
  const addFileToSession = (sessionId, fileObj) => {
    const state = getOrCreateSessionState(sessionId)
    state.uploadedFiles.push(fileObj)
  }

  // 从指定会话移除文件
  const removeFileFromSession = (sessionId, fileId) => {
    const state = sessionStates.value.get(sessionId)
    if (state) {
      state.uploadedFiles = state.uploadedFiles.filter(f => f.id !== fileId)
    }
  }

  // 清空指定会话的输入内容
  const clearSessionInput = (sessionId) => {
    const state = sessionStates.value.get(sessionId)
    if (state) {
      state.inputMessage = ''
    }
  }

  // 清空指定会话的文件列表
  const clearSessionFiles = (sessionId) => {
    const state = sessionStates.value.get(sessionId)
    if (state) {
      state.uploadedFiles = []
    }
  }

  // 置顶/取消置顶会话
  const pinSession = async (sessionId, isPinned) => {
    try {
      let response
      if (isPinned) {
        // 取消置顶
        response = await chatApi.unpinSession(sessionId)
      } else {
        // 置顶
        response = await chatApi.pinSession(sessionId)
      }
      
      // 更新本地会话状态
      const session = sessions.value.find(s => s.id === sessionId)
      if (session) {
        session.pinned = !isPinned
      }
      
      return response
    } catch (error) {
      console.error('置顶会话失败：', error)
      throw error
    }
  }

  // 删除会话
  const deleteSession = async (sessionId) => {
    try {
      await chatApi.deleteSession(sessionId)
      
      // 从本地会话列表中移除
      sessions.value = sessions.value.filter(s => s.id !== sessionId)
      
      // 从活跃会话中移除
      activeSessions.value.delete(sessionId)
      
      // 清理会话状态
      clearSessionState(sessionId)
      
      // 如果删除的是当前会话，切换到其他会话
      if (currentSession.value?.id === sessionId) {
        currentSession.value = sessions.value[0] || null
      }
      
      message.success('会话删除成功')
    } catch (error) {
      console.error('删除会话失败：', error)
      message.error('删除会话失败：' + (error.response?.data?.detail || error.message))
      throw error
    }
  }

  // 清理指定会话的状态
  const clearSessionState = (sessionId) => {
    const state = sessionStates.value.get(sessionId)
    if (state) {
      // 停止流式输出
      if (state.streamController) {
        state.streamController.abort()
      }
      // 关闭SSE连接
      if (state.eventSource) {
        state.eventSource.close()
        state.eventSource = null
      }
      // 重置状态
      state.messages = []
      state.loading = false
      state.isStreaming = false
      state.isRetrying = false
      state.lastUserMessage = null
      state.inputMessage = ''
      state.uploadedFiles = []
    }
  }

  // 检查会话的流式状态并恢复流式输出
  const checkAndResumeStreaming = async (sessionId) => {
    try {
      console.log(`[前端日志] 开始检查会话流式状态 - 会话ID: ${sessionId}`)
      const state = getOrCreateSessionState(sessionId)
      
      // 检查后端是否有流式数据
      console.log(`[前端日志] 调用后端流式状态接口 - 会话ID: ${sessionId}`)
      const streamingStatus = await chatApi.getStreamingStatus(sessionId)
      console.log(`[前端日志] 后端流式状态返回 - 会话ID: ${sessionId}, 状态:`, streamingStatus)
      
      if (streamingStatus.has_streaming) {
        console.log(`[前端日志] 会话有流式输出 - 会话ID: ${sessionId}, 消息ID: ${streamingStatus.message_id}, 是否完成: ${streamingStatus.is_final}`)
        // 会话有流式输出，开始恢复流程
        state.isStreaming = true
        
        // 激活会话，确保会话状态正确
        activateSession(sessionId)
        
        // 如果流式输出已完成，直接加载最终消息
        if (streamingStatus.is_final) {
          console.log(`[前端日志] 流式输出已完成，加载最终消息 - 会话ID: ${sessionId}`)
          await loadSessionMessages(sessionId)
          state.isStreaming = false
        } else {
          // 流式输出未完成，检查是否已有SSE连接
          console.log(`[前端日志] 检查SSE连接状态 - 会话ID: ${sessionId}, eventSource:`, state.eventSource)
          if (!state.eventSource || state.eventSource.readyState === EventSource.CLOSED) {
            console.log(`[前端日志] 需要重新建立SSE连接 - 会话ID: ${sessionId}, 连接状态: ${state.eventSource ? state.eventSource.readyState : '不存在'}`)
            // 没有有效的SSE连接，重新建立连接
            await resumeStreamingOutput(sessionId, streamingStatus.message_id)
          } else {
            console.log(`[前端日志] 已有有效的SSE连接 - 会话ID: ${sessionId}, 连接状态: ${state.eventSource.readyState}`)
            // 已有有效的SSE连接，确保会话状态正确
            state.isStreaming = true
          }
        }
      } else {
        console.log(`[前端日志] 会话没有流式输出 - 会话ID: ${sessionId}`)
        // 没有流式输出，正常加载消息
        state.isStreaming = false
      }
    } catch (error) {
      console.error('[前端日志] 检查流式状态失败：', error)
      const state = getOrCreateSessionState(sessionId)
      state.isStreaming = false
    }
  }

  // 恢复流式输出（SSE方案）
  const resumeStreamingOutput = async (sessionId, messageId) => {
    console.log(`[前端日志] 开始恢复流式输出 - 会话ID: ${sessionId}, 消息ID: ${messageId}`)
    const state = getOrCreateSessionState(sessionId)
    
    // 首先检查消息是否已经存在
    const existingMessageIndex = state.messages.findIndex(msg => msg.id === messageId)
    
    if (existingMessageIndex === -1) {
      // 消息不存在，创建AI消息占位符
      console.log(`[前端日志] 消息不存在，创建AI消息占位符 - 会话ID: ${sessionId}, 消息ID: ${messageId}`)
      const aiMessage = {
        id: messageId,
        session_id: sessionId,
        content: '',
        message_type: 'text',
        is_user: false,
        created_at: new Date().toISOString(),
        file_path: null,
        is_streaming: true
      }
      state.messages.push(aiMessage)
    } else {
      // 消息已存在，更新为流式状态
      console.log(`[前端日志] 消息已存在，更新为流式状态 - 会话ID: ${sessionId}, 消息ID: ${messageId}, 索引: ${existingMessageIndex}`)
      state.messages[existingMessageIndex].is_streaming = true
      state.messages[existingMessageIndex].is_final = false
    }
    
    // 建立SSE连接
    console.log(`[前端日志] 建立SSE连接 - 会话ID: ${sessionId}, 消息ID: ${messageId}`)
    const apiBaseUrl = import.meta.env.VITE_API_BASE_URL || 'http://localhost:8000'
    const authStore = useAuthStore()
    
    // 构建SSE URL，包含认证令牌
    let sseUrl = `${apiBaseUrl}/chat/sessions/${sessionId}/streaming-data-sse?message_id=${messageId}`
    if (authStore.token) {
      sseUrl += `&token=${encodeURIComponent(authStore.token)}`
      console.log(`[前端日志] SSE连接包含认证令牌 - 会话ID: ${sessionId}`)
    } else {
      console.log(`[前端日志] SSE连接无认证令牌 - 会话ID: ${sessionId}`)
    }
    
    const eventSource = new EventSource(sseUrl)
    
    eventSource.onmessage = (event) => {
      try {
        console.log(`[前端日志] 收到SSE消息 - 会话ID: ${sessionId}, 消息ID: ${messageId}, 数据:`, event.data)
        const data = JSON.parse(event.data)
        
        // 关键修复：检查当前会话是否仍然是活跃状态
        if (!state.isActive) {
          console.log(`[前端日志] 会话已非活跃状态，忽略SSE消息 - 会话ID: ${sessionId}, 消息ID: ${messageId}`)
          eventSource.close()
          state.eventSource = null
          return
        }
        
        // 更新AI消息内容
        const aiMessageIndex = state.messages.findIndex(msg => msg.id === messageId)
        if (aiMessageIndex !== -1) {
          if (data.content) {
            console.log(`[前端日志] 更新消息内容 - 会话ID: ${sessionId}, 消息ID: ${messageId}, 新增内容长度: ${data.content.length}`)
            state.messages[aiMessageIndex].content += data.content
          }
          
          // 如果流式输出已完成，关闭SSE连接
          if (data.is_final) {
            console.log(`[前端日志] 流式输出完成 - 会话ID: ${sessionId}, 消息ID: ${messageId}`)
            eventSource.close()
            state.messages[aiMessageIndex].is_streaming = false
            state.messages[aiMessageIndex].is_final = true
            state.isStreaming = false
            
            // 删除Redis中的流式数据
            api.delete(`/chat/sessions/${sessionId}/streaming-data?message_id=${messageId}`)
          }
        } else {
          console.log(`[前端日志] 找不到对应的AI消息 - 会话ID: ${sessionId}, 消息ID: ${messageId}`)
        }
      } catch (error) {
        console.error('[前端日志] 处理SSE消息失败：', error)
      }
    }
    
    eventSource.onerror = (error) => {
      console.error('[前端日志] SSE连接错误：', error)
      eventSource.close()
      state.isStreaming = false
      
      // 从数据库加载最终消息
      loadSessionMessages(sessionId)
    }
    
    // 保存SSE连接以便清理
    state.eventSource = eventSource
    console.log(`[前端日志] SSE连接建立完成 - 会话ID: ${sessionId}, 消息ID: ${messageId}, 连接状态: ${eventSource.readyState}`)
  }

  // 停止指定会话的SSE连接
  const stopStreamingPolling = (sessionId) => {
    const state = sessionStates.value.get(sessionId)
    if (state) {
      // 关闭SSE连接
      if (state.eventSource) {
        state.eventSource.close()
        state.eventSource = null
      }
    }
  }



  // 返回所有方法和状态
  return {
    // 会话列表相关
    sessions,
    currentSession,
    fetchSessions,
    createSession,
    selectSession,
    loadSessionMessages,
    
    // 输入和文件相关
    inputMessage,
    uploadedFiles,
    
    // 状态相关
    loading,
    isStreaming,
    isRetrying,
    canRetry,
    currentStreamController,
    
    // 会话管理相关
    getOrCreateSessionState,
    activateSession,
    deactivateSession,
    stopSessionStream,
    stopAllStreams,
    
    // 多会话并发支持
    sendMessageStreamToSession,
    getSessionState,
    clearSessionState,
    
    // 活跃会话管理
    activeSessionStates,
    
    // 会话活跃状态检查
    isSessionActive,
    
    // 会话加载状态检查
    isSessionLoading,
    
    // 获取会话消息
    getSessionMessages,
    
    // 会话文件管理
    getSessionFiles,
    getSessionInput,
    addFileToSession,
    removeFileFromSession,
    clearSessionInput,
    clearSessionFiles,
    
    // 会话操作
    pinSession,
    deleteSession,
    
    // 搜索开关管理
  getSessionEnableSearch,
  setSessionEnableSearch
}
})